# -*- coding: utf-8 -*-

from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login
from django.contrib import auth

from valida import existe_usuario,crea_usuario
from cuestionarios.main.forms import RegisterForm, LogInForm

# --------------------

def is_wap(request):
    return request.META['HTTP_ACCEPT'].find('application/vnd.wap.xhtml+xml') != -1

# --------------------

def set_content_type(is_wap, response):
    if is_wap:
        response['Content-Type'] = 'application/vnd.wap.xhtml+xml; charset=UTF-8'
    else:
        response['Content-Type'] = 'text/html; charset=UTF-8'

# --------------------

def standard_vars(request):
    return {'is_wap' : is_wap(request), 'authenticated' : request.user.is_authenticated()}

# GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL GENERAL 

def home(request, valid_user = True):
    # Revisar si es POST para validar al usuario y redirigirlo a home ya validado
    # Si no es valido se redirige a la pagina de error
    if request.method == 'POST' :
        # Validar que exista el usuario y si existe iniciar la sesion
        login2 = request.POST.get('login', None)
        password = request.POST.get('password', None)
        user = authenticate(username = login2, password = password)

        if user is not None:
            login(request, user)
            return HttpResponseRedirect("/home/")
        else:
            # Si el usuario no existe se redirige a la pagina que ofrece crearlo
            return HttpResponseRedirect("/error_login/")

    # Variables
    vars = standard_vars(request)
    if vars['authenticated']:
        vars['nombre'] = request.user.first_name
    else:
        vars['form'] =LogInForm()

    # Respuesta estandar
    response = render_to_response('home.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

# -------------------
def user_not_found(request):
    vars = standard_vars(request)
    response = render_to_response('error_login.html', vars )
    
    set_content_type(vars['is_wap'], response)
    return response

# --------------------

def error(request):
    vars = standard_vars(request)
    response = render_to_response('error.html', vars )
    set_content_type(vars['is_wap'], response)
    return response

# WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB WEB 

def register(request):
    # Variables
    vars = standard_vars(request)

    if vars['is_wap']:
        return HttpResponseRedirect('/error/')

    if not vars['authenticated'] :
        if request.method == 'POST':
            form = RegisterForm(request.POST)
            if form.is_valid():
                nombre = form.clean_data['nombre']
                username = form.clean_data['login']
                password = form.clean_data['password']
                crea_usuario(nombre, username, password)
                return HttpResponseRedirect('/register_ok/')
        else:
            form = RegisterForm()
        vars['form'] = form

    # Respuesta estandar
    response = render_to_response('register.html', vars )
    set_content_type(vars['is_wap'], response)

    return response

# --------------------

def register_ok(request):
    vars = standard_vars(request)

    if vars['is_wap']:
        return HttpResponseRedirect('/error/')

    response = render_to_response('reg_success.html', vars )
    set_content_type(vars['is_wap'], response)
    return response

